package com.gf.controller.mnue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gf.utils.Const;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/*
* 处理购物车中通过菜品的id来向购物车添加菜品的servlet
* */

@WebServlet(name = "adddish",urlPatterns = "/adddish")
public class AdddishServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        //首先获取当前的session对象
        JSONObject backjson = new JSONObject();
        //新建json对象
        HashMap<String ,Integer> shoppingcart =(HashMap<String ,Integer>) session.getAttribute("shoppingcart");
        //从session中取出购物车对象
        if(shoppingcart==null)shoppingcart=new  HashMap<String ,Integer>();
        //如果购物车没有被初始化就初始化购物车对象
        String dish_id = request.getParameter("dish_id");
        //键是商品的id,值是数量
        shoppingcart.put(dish_id,shoppingcart.get(dish_id)==null?1:shoppingcart.get(dish_id)+1);
        //判断购物车里有无对应的商品id有则加一无则设置为一
        session.setAttribute("shoppingcart",shoppingcart);
        //再讲购物车对象放回session中键为shoppingcart
        PrintWriter out = response.getWriter();
        //创建打印对象
        //设置正确的响应状态码和响应信息并输出
        response.setStatus(200);
        backjson.put("status",200);
        backjson.put("message", Const.ADDDISH_SUCESS);
        out.println(JSON.toJSON(backjson));
        out.flush();
        out.close();





    }
}
